# -*- coding: utf8 -*-

from puppy.query import QueryFilter
from puppy.model import Query


class TestError(Exception):
  def __init__(self, value):
    self.value = value
  def __str__(self):
    return "Error comparing term list "+repr(self.value)


class TestEqualFilter(QueryFilter):
  """Similar to an assert, compares the search terms with terms in a list."""
  
  def __init__(self, options=""):
    """Constructor for TestEqualFilter."""
    super(TestEqualFilter, self).__init__(options)
    self.info = "Compare the search terms with terms in a list, for debugging."
  
  
  def run(self, query):
    """Compare the search terms.
    
    As equal to other filters, extra terms are passed to the filter via its options['terms'] entry.  For convenience, the string returned from options['terms'] has '+' characters where there should be spaces.  This is resolved prior to query expansion.
    
    Parameters:
    
    * query (puppy.model.Opensearch.Query): original query
    
    Returns:
    
    * query (puppy.model.Opensearch.Query): original query or exception if both sets are different
    
    """
    original_terms = query.search_terms
    extra_terms = self.options['terms'].replace('+', ' ')
    A_set = set(original_terms.upper().split())
    B_set = set(extra_terms.upper().split())
    if A_set!=B_set:
      R_set = A_set.symmetric_difference(B_set)
      raise TestError(R_set)

    print "TestEqualFilter: Equal sets"
    #query is unchanged in any case
    return query
    
